﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain.Entities;
using WebNext.Domain;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using WebNext.UI.Utils;

namespace WebNext.UI.Models.Tags
{
	public class TagViewModel
	{
		public int Id
		{
			get;
			set;
		}

		public string Name
		{
			get;
			set;
		}

		public string Code
		{
			get;
			set;
		}

		public bool IsNameValid
		{
			get;
			private set;
		}

		public bool IsCodeValid
		{
			get;
			private set;
		}

		public TagViewModel(Tag tag) : this(tag.Id, tag.Name, tag.Code)
		{
		}

		public TagViewModel(int id, string name, string code)
		{
			this.Id = id;
			this.Name = name;
			this.Code = code;

			this.IsNameValid = true;
			this.IsCodeValid = true;
		}
		
		public ValidationResult Validate()
		{
			ValidationResult result = new ValidationResult();
			if (string.IsNullOrWhiteSpace(this.Name))
			{
				result.AddError(Properties.Resources.TagNameCannotBeEmpty);
				this.IsNameValid = false;
			}
			else if (this.Name.Length > Tag.MaxNameLength)
			{
				result.AddError(Properties.Resources.TagNameTooLong, Tag.MaxNameLength);
				this.IsNameValid = false;
			}

			if (string.IsNullOrWhiteSpace(this.Code))
			{
				result.AddError(Properties.Resources.TagCodeCannotBeEmpty);
				this.IsCodeValid = false;
			}
			else if (this.Code.Length > Tag.MaxCodeLength)
			{
				result.AddError(Properties.Resources.TagCodeTooLong, Tag.MaxCodeLength);
				this.IsCodeValid = false;
			}
			else
			{
				Regex regexValidator = new Regex("^[a-zA-Z0-9]+$");
				if (!regexValidator.IsMatch(this.Code))
				{
					result.AddError(Properties.Resources.TagCanOnlyConsistOfNumbersAndLetters);
					this.IsCodeValid = false;
				}
			}
			return result;
		}

		public void UpdateFrom(TagViewModel sourceTagModel)
		{
			this.Id = sourceTagModel.Id;
			this.Name = sourceTagModel.Name;
			this.IsNameValid = sourceTagModel.IsNameValid;
			this.Code = sourceTagModel.Code;
			this.IsCodeValid = sourceTagModel.IsCodeValid;
		}
	}
}